package com.xl.exp.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.xl.exp.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.slf4j.Logger;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
public class LoginController {

    @Resource
    private Producer captchaProducer;

    @RequestMapping("/")
    public String welcome(){
        return "index";
    }

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping(value = "/sublogin", method = RequestMethod.POST)
    public String sublogin(UserVo user, HttpServletRequest request, HttpServletResponse response) {

        if (!user.checkUser()) {
            return "error";
        }

        Subject subject = SecurityUtils.getSubject();
        try {
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(),
                    user.getUsername() + user.getPassword());
            subject.login(usernamePasswordToken);
            usernamePasswordToken.setRememberMe(true);
            subject.isAuthenticated();
        } catch (AuthenticationException e){
            try {
                response.setHeader("content-type","text/html;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.write("用户名或密码错误");
                writer.flush();
                writer.close();
                return null;
            } catch (IOException e1) {
                e1.printStackTrace();
                return e1.getMessage();
            }
        }catch (Exception e) {
            return e.getMessage();
        }

        return "redirect:index";
    }

    @RequestMapping(value = "/download/{id}")
    public String download(@PathVariable("id") String id){
        return "data/" + id + ".mp4" ;
    }

    @RequiresRoles("system")
    @RequestMapping(value = "/auth")
    public String auth(){
        return "auth" ;
    }

    public void check(){
        System.out.println("111");

    }



    @RequestMapping("/getCaptchaCode")
    public ModelAndView getCaptchaCode(HttpServletRequest request, HttpServletResponse response) throws IOException{
        HttpSession session = request.getSession();

        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        //生成验证码文本
        String capText = captchaProducer.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        System.out.println("生成验证码文本===="+capText);
        //利用生成的字符串构建图片
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);

        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

    @RequestMapping("/checkCaptchaCode")
    public void checkCaptchaCode(HttpServletRequest request, HttpServletResponse response,@RequestParam("captchaCode") String captchaCode){
        System.out.println("页面输入验证码===="+captchaCode);

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        String generateCode =(String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        String result = "";
        if(generateCode.equals(captchaCode)){
            result = "验证成功";
        }else{
            result = "输入错误";
        }
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.print(result);
        out.flush();
    }

    public static void main(String[] args) {
        // String pwd = new Md5Hash("111111", "mark").toString();
        // System.out.println(pwd);
        System.out.println(args instanceof Object);

    }

}
